package com.k2data.k2app.controller;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.k2data.k2app.common.MyConstant;
import com.k2data.k2app.common.OrikaMapperFactory;
import com.k2data.k2app.constant.Constant;
import com.k2data.k2app.constant.ResponseCode;
import com.k2data.k2app.domain.DeviceCond;
import com.k2data.k2app.domain.DeviceDTO;
import com.k2data.k2app.domain.MonitorDTO;
import com.k2data.k2app.domain.MonitorPointDTO;
import com.k2data.k2app.domain.po.*;
import com.k2data.k2app.domain.po.v1.Contacts;
import com.k2data.k2app.domain.po.v1.Event;
import com.k2data.k2app.exception.K2ResponseException;
import com.k2data.k2app.mapper.*;
import com.k2data.k2app.response.CommonResultResponse;
import com.k2data.k2app.response.PageInfo;
import com.k2data.k2app.response.ResponseHelper;
import com.k2data.k2app.service.*;
import com.k2data.k2app.utils.DateFormatterUtil;
import com.k2data.k2app.utils.StringUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lidong9144@163.com 17-3-15.
 */
@RestController
@RequestMapping("/devices")
public class DeviceController {

    @Autowired
    private ContactsService contactsService;
    @Autowired
    private EventV1Service eventV1Service;
    private final DeviceService deviceService;
    private final CustomerService customerService;
    private final EventFaultMapper eventFaultMapper;
    private final EventMaintenanceMapper eventMaintenanceMapper;
    private final DeviceMapper deviceMapper;
    private final MonitorService monitorService;
    private final MonitorPointMapper monitorPointMapper;
    private final DeviceOverviewMapper deviceOverviewMapper;
    private final DeviceOverviewService deviceOverviewService;
    private final SusbTimeIndexMapper susbTimeIndexMapper;
    private final SusbTimeIndexService susbTimeIndexService;

    @Autowired
    private  MyConstant myContant;

    @Autowired
    public DeviceController(DeviceService deviceService, CustomerService customerService,
                            EventFaultMapper eventFaultMapper, EventMaintenanceMapper eventMaintenanceMapper,
                            DeviceMapper deviceMapper, MonitorService monitorService,
                            MonitorPointMapper monitorPointMapper, DeviceOverviewMapper deviceOverviewMapper,
                            DeviceOverviewService deviceOverviewService,SusbTimeIndexMapper susbTimeIndexMapper,
                            SusbTimeIndexService susbTimeIndexService) {
        this.deviceService = deviceService;
        this.customerService = customerService;
        this.eventFaultMapper = eventFaultMapper;
        this.eventMaintenanceMapper = eventMaintenanceMapper;
        this.deviceMapper = deviceMapper;
        this.monitorService = monitorService;
        this.monitorPointMapper = monitorPointMapper;
        this.deviceOverviewMapper = deviceOverviewMapper;
        this.deviceOverviewService = deviceOverviewService;
        this.susbTimeIndexMapper = susbTimeIndexMapper;
        this.susbTimeIndexService=susbTimeIndexService;
    }

    @ApiOperation(value = "添加设备")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "device", value = "device", required = true, dataType = "Device", paramType = "body")
    })
    @PostMapping(value = "", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<CommonResultResponse> postDevice(@Valid @RequestBody Device device) throws Exception {
        return ResponseHelper.success(deviceService.insertDevice(device));
    }

    @ApiOperation(value = "更新设备")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "deviceId", required = true, dataType = "Long", paramType = "path"),
            @ApiImplicitParam(name = "device", value = "device", required = true, dataType = "Device", paramType = "body")
    })
    @PutMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<CommonResultResponse> putDevice(@PathVariable("id") Long id, @RequestBody Device device) throws Exception {
        device.setId(id);

        return ResponseHelper.success(deviceService.update(device));
    }
    @ApiOperation(value = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "Long", paramType = "path")
    })
    @DeleteMapping(value = "/{id}")
    public ResponseEntity<CommonResultResponse> delete(@PathVariable("id") Long id) throws Exception {
        return ResponseHelper.success(deviceService.delete(id));
//        return ResponseHelper.success(1);
    }

    @ApiOperation(value = "获取设备")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页大小(默认 30)", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "orderBy", value = "排序", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "name", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "type", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "status", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "customerId", value = "customerId", dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "deviceNo", value = "设备编号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "dataSource", value = "dataSource", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "withBoms", value = "是否关联查询部件", dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "当前登陆用户", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "years", value = "年份", allowMultiple = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "requireType", value = "客户端类型,wx:微信小程序", dataType = "string", paramType = "query")
    })
    @GetMapping(value = "")
    public ResponseEntity<CommonResultResponse> getDevices(
            @RequestParam(value = "pageNum", required = false) Integer pageNum,
            @RequestParam(value = "pageSize", required = false) Integer pageSize,
            @RequestParam(value = "orderBy", required = false) String orderBy,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "type", required = false) String type,
            @RequestParam(value = "status", required = false) String status,
            @RequestParam(value = "deviceNo", required = false) String deviceNO,
            @RequestParam(value = "customerId", required = false) Long customerId,
            @RequestParam(value = "userId", required = false) Long userId,
            @RequestParam(value = "dataSource", required = false) String dataSource,
            @RequestParam(value = "requireType", required = false) String requireType,
            @RequestParam(value = "years", required = false) List<String> years,
            @RequestParam(value = "withBoms", required = false) boolean withBoms
    ) throws Exception {
        Device cond = new Device();
        cond.setIsRoot(Constant.YES);
        cond.setOrderBy(orderBy);
        cond.setName(name);
        cond.setType(type);
        cond.setStatus(status);
        cond.setCustomerId(customerId);
        cond.setDataSource(dataSource);
        cond.setDeviceNo(deviceNO);
        cond.setUserId(deviceService.getUserId(userId));
        int pageNumReal = pageNum == null ? 1 : pageNum;
        int pageSizeReal = pageSize == null ? Constant.DEFAULT_PAGE_SIZE : pageSize;
        PageHelper.startPage(pageNumReal, pageSizeReal);
//        List<DeviceDTO> deviceDTOs = deviceService.selectDevicesWithoutCheckUser(cond);
        List<DeviceDTO> deviceDTOs = deviceService.selectDevices(cond);
        int count = deviceMapper.selectDevices(cond).size();
        PageInfo pageInfo = new PageInfo(pageNumReal, pageSizeReal, count);

        deviceDTOs.forEach(s->{
            s.setParentId(0L);
            s.setRootId(s.getId());
        });
        if(withBoms) {
            for (int i = 0; i < deviceDTOs.size() ; i++) {
                final Long deviceId = deviceDTOs.get(i).getId();
                List<DeviceDTO> deviceDTOs1 = deviceService.selectDeviceBomDeep(deviceId);
                if(deviceDTOs1.size()>0){
                    deviceDTOs.get(i).setChildren(deviceDTOs1.get(0).getChildren());
                }
            }
        }
        if(!StringUtils.isEmpty(requireType) && requireType.equals("wx")){
            for (int i = 0; i < deviceDTOs.size(); i++) {
                if(years == null || years.size() == 0){
                    Integer year = LocalDate.now().getYear();
                    years = Arrays.asList(String.valueOf(year));
                }
                Map<Integer, Map<Integer, Map>> integerMapMap = susbTimeIndexService.selectSusbGroupYear(deviceDTOs.get(i).getCustomerId(), deviceDTOs.get(i).getId(), years);
                Double hoursAll = 0D;
                String startTimeLast = "";
                for(Map.Entry<Integer, Map<Integer, Map>> yearEntry:integerMapMap.entrySet()){
                    Double hoursOfYear = 0D;
                    for(Map.Entry<Integer, Map> entry:yearEntry.getValue().entrySet()){
                        hoursOfYear += Double.parseDouble(entry.getValue().get("hours").toString());
                        List items = (List) entry.getValue().get("devices");
                        Map job = (Map) items.get(0);
                        if(job.get("startTimeLast") != null) {
                            startTimeLast = job.get("startTimeLast").toString();
                        }
                    }
                    hoursAll += hoursOfYear;
                }
                deviceDTOs.get(i).setHours(hoursAll);
                deviceDTOs.get(i).setStartTimeLast(startTimeLast);
            }
        }
        return ResponseHelper.success(deviceDTOs, pageInfo);
    }

    @ApiOperation(value = "获取设备")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "deviceId", required = true, dataType = "Long", paramType = "path")
    })
    @GetMapping(value = "/{id}")
    public ResponseEntity<CommonResultResponse> getDevice(@PathVariable("id") Long id) throws Exception {
        DeviceCond cond = new DeviceCond();
        cond.setDeviceId(id);

        return ResponseHelper.success(deviceService.selectDevice(cond));
    }

    @ApiOperation(value = "设备各状态数量")
    @GetMapping(value = "/types/count")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "customerId", value = "customerId", dataType = "Long", paramType = "query")
    })
    public ResponseEntity<CommonResultResponse> getTypesCount(@RequestParam(value = "customerId", required = false) Long customerId) throws Exception {
        DeviceCond cond = new DeviceCond();
        cond.setCustomerId(customerId);

        return ResponseHelper.success(deviceService.getDeviceTypeCount(cond));
    }

    @ApiOperation(value = "获取设备对应的文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "deviceId", required = true, dataType = "Long", paramType = "path")
    })
    @GetMapping(value = "/{id}/files")
    public ResponseEntity<CommonResultResponse> getFiles(@PathVariable("id") Long id) throws Exception {
        return ResponseHelper.success(deviceService.getFileUrls(id));
    }

    @ApiOperation(value = "获取设备联系人")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "deviceId", required = true, dataType = "Long", paramType = "path")
    })
    @GetMapping(value = "/{id}/contacts")
    public ResponseEntity<CommonResultResponse> getContacts(@PathVariable("id") Long id) throws Exception {
        return ResponseHelper.success(deviceService.getContactsByDevice(id));
    }

    @ApiOperation(value = "设备数量统计")
    @GetMapping(value = "/count")
    public ResponseEntity<CommonResultResponse> getCount() throws Exception {
        return ResponseHelper.success(deviceService.getCount());
    }

    @ApiOperation(value = "获取设备对应的客户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "deviceId", required = true, dataType = "Long", paramType = "path")
    })
    @GetMapping(value = "/{id}/customer")
    public ResponseEntity<CommonResultResponse> getDeviceCustomer(@PathVariable("id") Long id) throws Exception {
        DeviceCond cond = new DeviceCond();
        cond.setDeviceId(id);

        List<DeviceDTO> list = customerService.getDeviceCustomers(cond);
        if (list == null || list.isEmpty()) {
            return ResponseHelper.success();
        }

        return ResponseHelper.success(list.get(0));
    }

@ApiOperation(value = "设备所有事件")
@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "deviceId", required = true, dataType = "Long", paramType = "path"),
        @ApiImplicitParam(name = "types", value = "事件类型, 默认查全部", allowMultiple = true, dataType = "string", paramType = "query"),
        @ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "date", paramType = "query"),
        @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "date", paramType = "query"),
        @ApiImplicitParam(name = "orderBy", value = "排序(start_time desc , start_time asc, update_time desc, update_time asc)", dataType = "string", paramType = "query")
})
@GetMapping(value = "/{id}/events")
@Deprecated
public ResponseEntity<CommonResultResponse> getDeviceEvent(
        @PathVariable("id") Long id,
        @RequestParam(value = "types", required = false) List<String> types,
        @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
        @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate,
        @RequestParam(value = "orderBy", required = false) String orderBy) throws Exception {
    Event cond = new Event();
    cond.setDeviceId(id);
    cond.setStartTimeGreater(startDate);
    cond.setEndTimeGreater(endDate);
    cond.setFaultTypes(types);
    boolean flag = orderBy != null
            && !("start_time desc".equals(orderBy)
            || "start_time asc".equals(orderBy)
            || "update_time desc".equals(orderBy)
            || "update_time asc".equals(orderBy));
    if (flag) {
        throw new K2ResponseException(ResponseCode.GENERAL_CLIENT_ERROR, "Request param error, 'orderBy' must be one of (start_time desc , start_time asc, update_time desc, update_time asc).");
    }
    cond.setOrderBy(orderBy);

    return ResponseHelper.success(eventV1Service.list(cond));
}

    @ApiOperation(value = "故障列表")
    @GetMapping(value = "/{id}/events/faults")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "deviceId", required = true, dataType = "Long", paramType = "path"),
            @ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "date", paramType = "query"),
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "date", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页大小(默认 30)", dataType = "int", paramType = "query")
    })
    @Deprecated
    public ResponseEntity<CommonResultResponse> getFaultList(
            @PathVariable("id") Long id,
            @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            @RequestParam(value = "pageNum", required = false) Integer pageNum,
            @RequestParam(value = "pageSize", required = false) Integer pageSize) throws Exception {
        EventFault cond = new EventFault();
        cond.setDeviceId(id);
        cond.setStartTimeGreater(startDate);
        cond.setStartTimeLess(endDate);

        int pageNumReal = pageNum == null ? 1 : pageNum;
        int pageSizeReal = pageSize == null ? Constant.DEFAULT_PAGE_SIZE : pageSize;
        int count = eventFaultMapper.selectCount(cond);

        PageHelper.startPage(pageNumReal, pageSizeReal);
        PageInfo pageInfo = new PageInfo(pageNumReal, pageSizeReal, count);

        return ResponseHelper.success(eventFaultMapper.selectList(cond), pageInfo);
    }

    @ApiOperation(value = "维修列表")
    @GetMapping(value = "/{id}/events/maintenances")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "deviceId", required = true, dataType = "Long", paramType = "path"),
            @ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "date", paramType = "query"),
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "date", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页大小(默认 30)", dataType = "int", paramType = "query")
    })
    @Deprecated
    public ResponseEntity<CommonResultResponse> getMaintenanceList(
            @PathVariable("id") Long id,
            @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            @RequestParam(value = "pageNum", required = false) Integer pageNum,
            @RequestParam(value = "pageSize", required = false) Integer pageSize) throws Exception {
        EventMaintenance cond = new EventMaintenance();
        cond.setDeviceId(id);
        cond.setStartTimeGreater(startDate);
        cond.setStartTimeLess(endDate);

        int pageNumReal = pageNum == null ? 1 : pageNum;
        int pageSizeReal = pageSize == null ? Constant.DEFAULT_PAGE_SIZE : pageSize;
        int count = eventMaintenanceMapper.selectCount(cond);

        PageHelper.startPage(pageNumReal, pageSizeReal);
        PageInfo pageInfo = new PageInfo(pageNumReal, pageSizeReal, count);

        return ResponseHelper.success(eventMaintenanceMapper.selectList(cond), pageInfo);
    }

    @ApiOperation(value = "bom")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "deviceId", required = true, dataType = "Long", paramType = "path"),
            @ApiImplicitParam(name = "type", value = "type(wide, deep)", dataType = "Long", paramType = "query")
    })
    @GetMapping(value = "/{id}/boms")
    public ResponseEntity<CommonResultResponse> getDeviceBom(
            @PathVariable("id") Long id,
            @RequestParam(value = "type", required = false) String type) throws Exception {

        if ("deep".equals(type)) {
            return ResponseHelper.success(deviceService.selectDeviceBomDeep(id));
        }

        return ResponseHelper.success(deviceService.selectDeviceBomWide(id));
    }

    @ApiOperation(value = "测点")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "deviceId", required = true, dataType = "Long", paramType = "path"),
            @ApiImplicitParam(name = "sensor-type", value = "sensorTYpe", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "channel-id", value = "channelId", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "type", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "is-component", value = "是否为部件", dataType = "int", paramType = "query")
    })
    @GetMapping(value = "/{id}/monitors/old")
    public ResponseEntity<CommonResultResponse> getDeviceMonitor(
            @PathVariable("id") Long id,
//            @RequestParam(value = "q", required = false) String[] qs,
            @RequestParam(value = "kmxvalue", required = false) String kmxvalue,
            @RequestParam(value = "sensor-type", required = false) String sensorType,
            @RequestParam(value = "channel-id", required = false) Integer channelId,
            @RequestParam(value = "group", required = false) String group,
            @RequestParam(value = "type", required = false) Integer type,
            @RequestParam(value = "is-component", required = false) Integer isComponent
    ) throws Exception {
        DeviceCond cond = new DeviceCond();
        if (Constant.YES.equals(isComponent)) {
            cond.setDeviceId(id);
        } else {
            cond.setRootId(id);
        }
        cond.setKmxValue(kmxvalue);
        cond.setSensorType(sensorType);
        cond.setChannelId(channelId);
        if (type != null) {
            cond.setType(type);
        }

        List<MonitorDTO> list = monitorService.selectAllVariables(cond);
        if (group != null) {
            Map<String, List<MonitorDTO>> map = list.parallelStream().collect(Collectors.groupingBy(MonitorDTO::getSensorType));

            Map<String, Object> groupMap = Maps.newHashMap();
            for (Map.Entry<String, List<MonitorDTO>> group1 : map.entrySet()) {
                groupMap.put(
                        group1.getKey(),
                        group1.getValue()
                                .parallelStream()
                                .collect(Collectors.groupingBy(MonitorDTO::getSensorName))
                );
            }

            return ResponseHelper.success(groupMap);
        }

        return ResponseHelper.success(list);
    }

    @ApiOperation(value = "测点")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "deviceId", required = true, dataType = "Long", paramType = "path"),
            @ApiImplicitParam(name = "sensor-type", value = "sensorTYpe", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "channel-id", value = "channelId", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "type", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "is-component", value = "是否为部件", dataType = "int", paramType = "query")
    })
    @GetMapping(value = "/{id}/monitors")
    public ResponseEntity<CommonResultResponse> getDeviceMonitor1(
            @PathVariable("id") Long id,
//            @RequestParam(value = "q", required = false) String[] qs,
            @RequestParam(value = "kmxvalue", required = false) String kmxvalue,
            @RequestParam(value = "sensor-type", required = false) String sensorType,
            @RequestParam(value = "channel-id", required = false) Integer channelId,
            @RequestParam(value = "group", required = false) String group,
            @RequestParam(value = "varibleIsTemplate", required = false) String varibleIsTemplate,
            @RequestParam(value = "type", required = false) Integer type,
            @RequestParam(value = "is-component", required = false) Integer isComponent
    ) throws Exception {
        DeviceCond cond = new DeviceCond();
        if (Constant.YES.equals(isComponent)) {
            cond.setDeviceId(id);
        } else {
            cond.setRootId(id);
        }
        cond.setKmxValue(kmxvalue);
        cond.setSensorType(sensorType);
        cond.setChannelId(channelId);
        if (type != null) {
            cond.setType(type);
        }

        List<MonitorDTO> list = monitorService.selectAllVariablesCopy(cond);
        if (group != null) {
            Map<String, List<MonitorDTO>> map = list.parallelStream().collect(Collectors.groupingBy(MonitorDTO::getSensorType));
            if(varibleIsTemplate == null ){
                // 不去重复变量
                Map<String, Object> groupMap = Maps.newHashMap();
                for (Map.Entry<String, List<MonitorDTO>> group1 : map.entrySet()) {
                    groupMap.put(
                            group1.getKey(),
                            group1.getValue()
                                    .parallelStream()
                                    .collect(Collectors.groupingBy(MonitorDTO::getSensorName))
                    );
                }
                return ResponseHelper.success(groupMap);
            }else{
                // 去除重复变量
                Map<String, Map<String, List<MonitorDTO>>> groupMap = Maps.newHashMap();
                for (Map.Entry<String, List<MonitorDTO>> group1 : map.entrySet()) {
                    Map<String,List<MonitorDTO>> map1 = group1.getValue()
                            .parallelStream()
                            .collect(Collectors.groupingBy(MonitorDTO::getSensorName));


                    for (Map.Entry<String, List<MonitorDTO>> group2 : map1.entrySet()) {
                        List<String> variblesNameDistinck = Lists.newArrayList();
                        List<MonitorDTO> variblesDistinck = Lists.newArrayList();
                        group2.getValue().forEach(s->{
                            if(!variblesNameDistinck.contains(s.getVariableNameEn())){
                                variblesNameDistinck.add(s.getVariableNameEn());
                                variblesDistinck.add(s);
                            }
                        });
                        map1.put(group2.getKey(),variblesDistinck);
                    }
                    groupMap.put(
                            group1.getKey(),
                            map1);
                }
                return ResponseHelper.success(groupMap);
            }
        }

        return ResponseHelper.success(list);
    }





    @ApiOperation(value = "channelId")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "deviceId", required = true, dataType = "Long", paramType = "path")
    })
    @GetMapping(value = "/{id}/channel-ids")
    public  ResponseEntity<CommonResultResponse> getChannelId(@PathVariable("id") Long id) throws Exception {
        List<MonitorPoint> list = monitorPointMapper.selectChannelIdByDevice(id);

        if (list.isEmpty()) {
            return ResponseHelper.success();
        }

        Map<String, MonitorPoint> cache = Maps.newHashMap();
        for (MonitorPoint monitorPoint : list) {
            if (cache.get(monitorPoint.getSensorType()) == null) {
                MonitorPoint init = new MonitorPoint();
                init.setSensorType(monitorPoint.getSensorType());
                init.setNameEn(monitorPoint.getNameEn());
                init.setFieldGroup(myContant.getFieldGroup(monitorPoint.getNameEn()));
                init.setChannelIds(new TreeSet<Map<String, Object>>(Comparator.comparing(o -> ((Integer) o.get("id")))));
                cache.put(monitorPoint.getSensorType(), init);
            }

            MonitorPoint inner = cache.get(monitorPoint.getSensorType());
            Map<String, Object> innerMap = Maps.newHashMap();
            innerMap.put("id", monitorPoint.getChannelId());
            innerMap.put("name", monitorPoint.getChannelName());
            innerMap.put("state", monitorPoint.getState());
            innerMap.put("bearingName", monitorPoint.getBearingName());
            innerMap.put("rotatDirec", monitorPoint.getRotatDirec());
            innerMap.put("samples", monitorPoint.getSamples());
            innerMap.put("normalRevolution", monitorPoint.getNormalRevolution());
            innerMap.put("susdRevolutution",monitorPoint.getSusdRevolution());
            innerMap.put("deltaSpeed",monitorPoint.getDeltaSpeed());
            innerMap.put("activity",monitorPoint.getActivity());
            innerMap.put("orientDegree",monitorPoint.getOrientDegree());
            innerMap.put("keyId",monitorPoint.getKeyId());
            inner.getChannelIds().add(innerMap);
        }

        List<MonitorPoint> result = Lists.newArrayList();
        for (Map.Entry<String, MonitorPoint> entry : cache.entrySet()) {
            result.add(entry.getValue());
        }

        return ResponseHelper.success(result);
    }

    @ApiOperation(value = "channelId")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "deviceId", required = true, dataType = "Long", paramType = "path")
    })
    @GetMapping(value = "/{id}/channel-ids-old")
    public  ResponseEntity<CommonResultResponse> getChannelIdOld(@PathVariable("id") Long id) throws Exception {
        List<MonitorPoint> list = monitorPointMapper.selectChannelId(id);

        if (list.isEmpty()) {
            return ResponseHelper.success();
        }

        Map<String, MonitorPoint> cache = Maps.newHashMap();
        for (MonitorPoint monitorPoint : list) {
            if (cache.get(monitorPoint.getSensorType()) == null) {
                MonitorPoint init = new MonitorPoint();
                init.setSensorType(monitorPoint.getSensorType());
                init.setChannelIds(new TreeSet<>(Comparator.comparing(o -> ((Integer) o.get("id")))));
                cache.put(monitorPoint.getSensorType(), init);
            }
            MonitorPoint inner = cache.get(monitorPoint.getSensorType());
            Map<String, Object> innerMap = Maps.newHashMap();
            innerMap.put("id", monitorPoint.getChannelId());
            innerMap.put("name", monitorPoint.getChannelName());
            innerMap.put("state", monitorPoint.getState());
            innerMap.put("bearingName", monitorPoint.getBearingName());
            innerMap.put("rotatDirec", monitorPoint.getRotatDirec());
            innerMap.put("samples", monitorPoint.getSamples());
            innerMap.put("normalRevolution", monitorPoint.getNormalRevolution());
            inner.getChannelIds().add(innerMap);
        }

        List<MonitorPoint> result = Lists.newArrayList();
        for (Map.Entry<String, MonitorPoint> entry : cache.entrySet()) {
            result.add(entry.getValue());
        }

        return ResponseHelper.success(result);
    }

    @ApiOperation(value = "设备测点")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "root_id", value = "根节点id", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "device_id", value = "部件id", required = false, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "monitorPointId", value = "测点id", required = false, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "channelId", value = "channelId", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "isGroup", value = "是否按照测点名称分组", required = false, dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "groupType", value = "分组类型，返回结果格式", required = false, dataType = "int", paramType = "query")
    })
    @GetMapping(value = "/points")
    public ResponseEntity<CommonResultResponse> getDevicePoints(
            @RequestParam(value = "root_id") Long rootId,
            @RequestParam(value = "device_id",required = false) Long deviceId,
            @RequestParam(value = "monitorPointId",required = false) Long monitorPointId,
            @RequestParam(value = "channelId",required = false)Integer channelId,
            @RequestParam(value = "isGroup",required = false) boolean isGroup,
            @RequestParam(value = "groupType",required = false) Integer groupType) throws Exception {
        DeviceCond cond = new DeviceCond();
        cond.setRootId(rootId);
        cond.setDeviceId(deviceId);
        cond.setId(monitorPointId);
        cond.setChannelId(channelId);
        List<MonitorDTO> monitorDTOs = monitorService.selectPointsCopy(cond);
        if(isGroup){
            Map<String, List<MonitorDTO>> map = monitorDTOs.parallelStream().collect(Collectors.groupingBy(MonitorDTO::getSensorName));
            if(groupType !=null && groupType == 2){
                List<MonitorPointDTO> list = Lists.newArrayList();
                map.forEach((k,v)->{
                    MonitorDTO monitorDTO = v.get(0);
                    MonitorPointDTO dto = OrikaMapperFactory.getMapper().map(monitorDTO, MonitorPointDTO.class);
                    dto.setMonitorDTOs(v);
                    list.add(dto);
                });
                return ResponseHelper.success(list);
            }else{
                return ResponseHelper.success(map);
            }

        } else {
            return ResponseHelper.success(monitorService.selectPointsCopy(cond));
        }

    }

    @ApiOperation(value = "设备测点")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "Long", paramType = "path")
    })
    @GetMapping(value = "/points/{id}")
    public ResponseEntity<CommonResultResponse> getDevicePoint(@PathVariable("id") Long id) throws Exception {
//        DeviceCond cond = new DeviceCond();
//        cond.setId(id);
//
//        return ResponseHelper.success(monitorService.selectDevicePoints(cond));
        DeviceCond cond = new DeviceCond();
        cond.setId(id);
        List<MonitorDTO> monitorDTOs = monitorService.selectPointsCopy(cond);
        if(monitorDTOs.size()==1){
            return ResponseHelper.success(monitorDTOs.get(0));
        }
        return ResponseHelper.success(new MonitorDTO());
    }

    @ApiOperation(value = "添加设备联系人")
    @PostMapping(value = "/{id}/contacts", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "Long", paramType = "path"),
            @ApiImplicitParam(name = "contacts", value = "contacts", required = true, dataType = "Contacts", paramType = "body")
    })
    public ResponseEntity<CommonResultResponse> postContact(@PathVariable("id") Long id,
                                                                @RequestBody Contacts contacts) throws Exception {
        return ResponseHelper.success(contactsService.insert(contacts,id));
    }

    @ApiOperation(value = "添加设备测点")
    @PostMapping(value = "/points", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "point", value = "points", required = true, dataType = "RDeviceMonitorPoint", paramType = "body")
    })
    public ResponseEntity<CommonResultResponse> postDevicePoints(@RequestBody RDeviceMonitorPoint point) throws Exception {
        return ResponseHelper.success(monitorService.insertDevicePointCopy(point));
    }

    @ApiOperation(value = "同步模板测点到设备测点")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "同步类型，是否是第一次同步", required = false, dataType = "String", paramType = "query"),
    })
    @GetMapping(value = "/points/syn")
    public ResponseEntity<CommonResultResponse> postTemplatePoints(@RequestParam(value = "type",required = false) String type) throws Exception {
        return ResponseHelper.success(monitorService.synTemplatePoint(type));
    }

    @ApiOperation(value = "同步模板测点到设备测点")
    @GetMapping(value = "/points/syn/same")
    public ResponseEntity<CommonResultResponse> postTemplatePointsSame() throws Exception {
        return ResponseHelper.success(monitorService.synTemplatePointSame());
    }

    //    @ApiOperation(value = "修改设备测点")
//    @PutMapping(value = "/points/{rid}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "rid", value = "rid", required = true, dataType = "Long", paramType = "path"),
//            @ApiImplicitParam(name = "point", value = "points", required = true, dataType = "RDeviceMonitorPoint", paramType = "body")
//    })
//    public ResponseEntity<CommonResultResponse> putDevicePoints(@PathVariable("rid") Long rid,
//                                                                @RequestBody RDeviceMonitorPoint point) throws Exception {
//        point.setId(rid);
//        point.setState(0);
//        return ResponseHelper.success(monitorService.updateDevicePoint(point));
//    }
    @ApiOperation(value = "修改设备测点")
    @PutMapping(value = "/points/{rid}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rid", value = "rid", required = true, dataType = "Long", paramType = "path"),
            @ApiImplicitParam(name = "point", value = "points", required = true, dataType = "RDeviceMonitorPointCopy", paramType = "body")
    })
    public ResponseEntity<CommonResultResponse> putDevicePoints(@PathVariable("rid") Long rid,
                                                                @RequestBody RDeviceMonitorPointCopy point) throws Exception {
        point.setId(rid);
        point.setState(0);
        return ResponseHelper.success(monitorService.updateDevicePointCopy(point));
    }

    @ApiOperation(value = "删除设备测点")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rid", value = "rid", required = true, dataType = "Long", paramType = "path")
    })
    @DeleteMapping(value = "/points/{rid}")
    public ResponseEntity<CommonResultResponse> deleteDevicePoint(@PathVariable("rid") Long rid) throws Exception {
        return ResponseHelper.success(monitorService.deleteDevicePointCopy(rid));
    }

    @ApiOperation(value = "设备测点变量")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceId", value = "deviceId", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "monitorPointId", value = "monitorPointId", dataType = "Long", paramType = "query")
    })
    @GetMapping(value = "/monitors/variables")
    public ResponseEntity<CommonResultResponse> getDeviceVariables(
            @RequestParam(value = "deviceId", required = false) Long deviceId,
            @RequestParam(value = "monitorPointId", required = false) Long monitorPointId) throws Exception {
        DeviceCond cond = new DeviceCond();
        cond.setDeviceId(deviceId);
        cond.setMonitorPointId(monitorPointId);

        return ResponseHelper.success(monitorService.selectTDeviceVariables(cond));
    }
    @ApiOperation(value = "添加监控指标")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "monitorValue", value = "monitorValue", required = true, dataType = "MonitorVariable", paramType = "body")
    })
    @PostMapping(value = "/monitors/variables", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<CommonResultResponse> postMonitorValue(@Valid @RequestBody MonitorVariable monitorValue) throws Exception {
        return ResponseHelper.success(monitorService.insertVariable(monitorValue));
    }

    @ApiOperation(value = "更新监控指标")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "Long", paramType = "path"),
            @ApiImplicitParam(name = "monitorValue", value = "monitorValue", required = true, dataType = "MonitorVariable", paramType = "body")
    })
    @PutMapping(value = "/monitors/variables/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<CommonResultResponse> putMonitorValue(@PathVariable("id") Long id, @RequestBody MonitorVariable monitorValue) throws Exception {
        monitorValue.setId(id);

        return ResponseHelper.success(monitorService.updateVariable(monitorValue));
    }

    @ApiOperation(value = "删除监控指标")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "Long", paramType = "path")
    })
    @DeleteMapping(value = "/monitors/variables/{id}")
    public ResponseEntity<CommonResultResponse> deleteMonitorValue(@PathVariable("id") Long id) throws Exception {
        return ResponseHelper.success(monitorService.deleteVariable(id));
    }

    @ApiOperation(value = "设备测点变量")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "Long", paramType = "path")
    })
    @GetMapping(value = "/monitors/variables/{id}")
    public ResponseEntity<CommonResultResponse> getDeviceVariable(@PathVariable("id") Long id) throws Exception {
        DeviceCond cond = new DeviceCond();
        cond.setId(id);

        return ResponseHelper.success(monitorService.selectTDeviceVariables(cond));
    }


    @ApiOperation(value = "设备测点阈值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceId", value = "deviceId", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "monitorPointId", value = "monitorPointId", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "variableId", value = "variableId", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "deviceNo", value = "deviceNo", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "channelId", value = "channelId", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "isTemplateVariable", value = "传递的测点变量是否是模板", dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "level", value = "level", dataType = "int", paramType = "query")
    })
    @GetMapping(value = "/monitors/limits")
    public ResponseEntity<CommonResultResponse> getDeviceLimitValues(
            @RequestParam(value = "deviceId", required = false) Long deviceId,
            @RequestParam(value = "monitorPointId", required = false) Long monitorPointId,
            @RequestParam(value = "variableId", required = false) Long variableId,
            @RequestParam(value = "deviceNo", required = false) String deviceNo,
            @RequestParam(value = "channelId", required = false) Integer channelId,
            @RequestParam(value = "level", required = false) Integer level,
            @RequestParam(value = "isTemplateVariable",required = false) boolean isTemplateVariable
    ) throws Exception {
        DeviceCond cond = new DeviceCond();
        cond.setDeviceId(deviceId);
        cond.setMonitorPointId(monitorPointId);
        cond.setVariableId(variableId);
        cond.setDeviceNo(deviceNo);
        cond.setChannelId(channelId);
        cond.setLevel(level);

        List list = Lists.newArrayList();
        if(isTemplateVariable){
            cond.setTVariableId(variableId);
            list = monitorService.selectLimitValueByTVarible(cond);
        }else{
            list = monitorService.selectTDeviceLimit(cond);
        }

        return ResponseHelper.success(list);
    }



    @ApiOperation(value = "添加阀值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "limitValue", value = "limitValue", required = true, dataType = "MonitorLimitValue", paramType = "body")
    })
    @PostMapping(value = "/monitors/limits", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<CommonResultResponse> postMonitorPoint(@Valid @RequestBody MonitorLimitValue limitValue) throws Exception {
        return ResponseHelper.success(monitorService.insertLimit(limitValue));
    }

    @ApiOperation(value = "更新阀值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "Long", paramType = "path"),
            @ApiImplicitParam(name = "limitValue", value = "limitValue", required = true, dataType = "MonitorLimitValue", paramType = "body"),
            @ApiImplicitParam(name = "limit2kmx", value = "是否同步到kmx", required = false, dataType = "boolean", paramType = "query")
    })
    @PutMapping(value = "/monitors/limits/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<CommonResultResponse> putMonitorPoint(@PathVariable("id") Long id,
                                                                @RequestBody MonitorLimitValue limitValue,
                                                                @RequestParam(value = "limit2kmx",required = false) boolean limit2kmx) throws Exception {
        limitValue.setId(id);
        Long aLong = 0L;
        if(limit2kmx){
            aLong = monitorService.updateLimitAndLimit2Kmx(limitValue);
        }else {
            monitorService.updateLimit(limitValue);
        }
        return ResponseHelper.success(aLong);
    }

    @ApiOperation(value = "删除阀值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "Long", paramType = "path")
    })
    @DeleteMapping(value = "/monitors/limits/{id}")
    public ResponseEntity<CommonResultResponse> putMonitorPoint(@PathVariable("id") Long id) throws Exception {
        return ResponseHelper.success(monitorService.deleteLimitFlag(id));
    }


    @ApiOperation(value = "改状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceNo", value = "deviceNo", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "status", required = true, dataType = "string", paramType = "query")
    })
    @PutMapping(value = "/status")
    public ResponseEntity<CommonResultResponse> changeStatus(
            @RequestParam("deviceNo") String deviceNo,
            @RequestParam("status") String status
    ) throws Exception {
        return ResponseHelper.success(deviceMapper.updateStatus(status, deviceNo));
    }

    @ApiOperation(value = "overview")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceId", value = "deviceId", required = true, dataType = "Long", paramType = "path")
    })
    @GetMapping(value = "/{deviceId}/overview")
    public ResponseEntity<CommonResultResponse> getOverview(@PathVariable("deviceId") Long deviceId) throws Exception {
        DeviceCond cond = new DeviceCond();
        cond.setDeviceId(deviceId);
        List<DeviceOverview> deviceOverviews = deviceOverviewMapper.selectOverview(cond);
        deviceOverviews.forEach(s->{
            s.setFieldgroupId(myContant.getFieldGroup(s.getFieldgroupId()));
        });
        //键相通道特殊处理
        for (DeviceOverview deviceOverview:deviceOverviews) {
            //如果是speed则修改channel_id为键相Id对应的channel_id(在r_device_monitor_point表中根据deviceId和keyId查询)
            if(deviceOverview.getVariable().equals("speed")){
                DeviceOverview dev=deviceOverviewMapper.selectChannel(deviceId,deviceOverview.getChannelId());
                if(dev!=null){
                    deviceOverview.setChannelId(dev.getChannelId());
                    deviceOverview.setName(dev.getName());
                }
            }
            //如果type为1且variable为direc，则将variable改为有效值rms
            if(deviceOverview.getType()==1&&deviceOverview.getVariable().equals("direc")){
                deviceOverview.setVariable("rms");
            }
        }
        //tcs总貌图返回name特殊处理
        for (DeviceOverview deviceOverview:deviceOverviews) {
            if(deviceOverview.getFieldgroupId().indexOf("tcs")!=-1){
                deviceOverview.setName(deviceOverview.getVariableName());
            }
        }

        return ResponseHelper.success(deviceOverviews);
    }

    @ApiOperation(value = "overviewdata")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceId", value = "deviceId", required = true, dataType = "Long", paramType = "path")
    })
    @GetMapping(value = "/{deviceId}/overviewdata")
    public ResponseEntity<CommonResultResponse> getOverviewData(
            @PathVariable("deviceId") Long deviceId
    ) throws Exception {
        return ResponseHelper.success(deviceOverviewService.getDeviceOverviewData(deviceId));
    }

    @ApiOperation(value = "启停机")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceId", value = "deviceId", required = true, dataType = "Long", paramType = "path"),
            @ApiImplicitParam(name = "order", value = "order", required = true, dataType = "string", paramType = "query")
    })
    @GetMapping(value = "/{deviceId}/susb")
    public ResponseEntity<CommonResultResponse> getSusb(@PathVariable("deviceId") Long deviceId, @RequestParam("order") String order) throws Exception {
        SusbTimeIndex cond = new SusbTimeIndex();
        cond.setDeviceId(deviceId);
        cond.setKind(1);
        cond.setOrder(order);
        List<SusbTimeIndex> susbTimeIndexs= susbTimeIndexMapper.selectSusb(cond);
        List<SusbTimeIndex> susbEffective=Lists.newArrayList();
        List<SusbTimeIndex> susbReturn=Lists.newArrayList();
        //去除启停机除type为0,1的数据
        for (SusbTimeIndex susbTimeIndex:susbTimeIndexs) {
            if(susbTimeIndex.getType()==0||susbTimeIndex.getType()==1){
                susbEffective.add(susbTimeIndex);
            }
        }
        //去除启停机重复启启停停的数据
        if(!susbEffective.isEmpty()){
            susbReturn.add(susbEffective.get(0));
            for (int i=1;i<susbEffective.size();i++ ) {
                if(!susbEffective.get(i).getType().equals(susbEffective.get(i-1).getType())){
                    susbReturn.add(susbEffective.get(i));
                }
            }
        }

        return ResponseHelper.success(susbReturn);
    }

    @ApiOperation(value = "模拟插入启停机数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceId", value = "deviceId", required = true, dataType = "Long", paramType = "path"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "String", paramType = "query"),
    })
    @PostMapping(value = "/{deviceId}/susb/insert", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<CommonResultResponse> getSusbs(@PathVariable("deviceId") Long deviceId,
                                                         @RequestParam(value = "startTime", required = false) String  startTime,
                                                         @RequestParam(value = "endTime", required = false) String endTime) throws Exception {
        SusbTimeIndex susbTimeIndex = new SusbTimeIndex();
        susbTimeIndex.setDeviceId(deviceId);
        LocalDateTime localDateTime1 = DateFormatterUtil.convertToType(LocalDateTime.class,startTime);
        LocalDateTime localDateTime2 = DateFormatterUtil.convertToType(LocalDateTime.class,endTime);
        ZoneId zoneId = ZoneId.of("UTC+1");
        ZonedDateTime start = ZonedDateTime.of(localDateTime1.getYear(), localDateTime1.getMonthValue(), localDateTime1.getDayOfMonth(),
                localDateTime1.getHour(), localDateTime1.getMinute(), localDateTime1.getSecond(),000, zoneId);
        ZonedDateTime end = ZonedDateTime.of(localDateTime2.getYear(), localDateTime2.getMonthValue(), localDateTime2.getDayOfMonth(),
                localDateTime2.getHour(), localDateTime2.getMinute(), localDateTime2.getSecond(),000, zoneId);
        susbTimeIndex.setStartTime(start);
        susbTimeIndex.setStopTime(end);
        susbTimeIndex.setDeviceId(deviceId);
        susbTimeIndex.setKind(1);
        susbTimeIndex.setKeyId(1);
        susbTimeIndex.setType(1);
        susbTimeIndex.setCreateTime(start);
        susbTimeIndex.setUpdateTime(end);
        susbTimeIndex.setTimeZone("GMT-0");
        return ResponseHelper.success(susbTimeIndexMapper.insert(susbTimeIndex));
    }


    @ApiOperation(value = "仪表盘显示信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "deviceId", required = true, dataType = "Long", paramType = "path"),
            @ApiImplicitParam(name = "year", value = "年份", dataType = "String", paramType = "query")
    })
    @GetMapping(value = "/{id}/panel")
    public ResponseEntity<CommonResultResponse> getDeviceMonitor1(
            @PathVariable("id") Long id,
            @RequestParam(value = "year", required = false) Integer  year

    ) throws Exception {

        Map<String,Object> reMap=Maps.newHashMap();
        //显示机组状态等级
        Device device = deviceMapper.selectById(id);
        reMap.put("status",device.getStatus());
        //显示启停机次数
        long susbNUm = susbTimeIndexService.susbNum(id,year);
        reMap.put("susbNUm",susbNUm);
        //显示该设备的转速
        List<DeviceOverview> list=deviceOverviewService.getPanel(id);
        reMap.put("speedList",list);
        return ResponseHelper.success(reMap);
    }

    @ApiOperation(value = "设备状态统计")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dataSource", value = "dataSource", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "showType", value = "allStatus:全部状态 onlySelf:有状态的显示", dataType = "String", paramType = "query")
    })
    @GetMapping(value = "/status/count")
    public ResponseEntity<CommonResultResponse> getDevicesStatus(
            @RequestParam(value = "dataSource", required = false) String dataSource,
            @RequestParam(value = "showType", required = false) String showType
    ) throws Exception {
        Device cond = new Device();
        cond.setIsRoot(Constant.YES);
        cond.setDataSource(dataSource);
        showType=showType==null?"allStatus":showType;
        return ResponseHelper.success(deviceService.getDeviceStatusCount(cond,showType));
    }
}


